"use client"
import React, {useEffect, useState} from "react";
import {Input, Form, Select, Card, Switch, Radio, Tooltip,} from "antd";
import baseInformationClass from "@/components/properties-panel-extension/components/index.module.css";
import {generateUniqueId} from "@/utils/Z";
import {InfoCircleOutlined} from "@ant-design/icons";

interface MyComponentProps {
    bpmnInstance: any;
}

interface DefaultOptionType {
    value: string;
    label: string;
}

// 添加会签设置相关类型
interface MultiInstanceConfig {
    isSequential: boolean // 是否串行
    loopCardinality: string // 循环次数
    collection: string // 集合表达式
    elementVariable: string // 元素变量
    completionCondition: string // 完成条件
}


// 事件配置组件
const MultiInstanceConfigurationView: React.FC<MyComponentProps> = (props: any) => {
    const {bpmnInstance} = props
    const {modeling, modeler, moddle, bpmnElement = {}, elementRegistry, bpmnFactory} = bpmnInstance
    const [baseInfo, setBaseInfo] = useState<any>();

    const [multiInstanceConfig, setMultiInstanceConfig] = useState<MultiInstanceConfig>({
        isSequential: false,
        loopCardinality: '',
        collection: '',
        elementVariable: '',
        completionCondition: '',
    });
    const [isMultiInstance, setIsMultiInstance] = useState<boolean>(false);
    useEffect(() => {
        if (bpmnElement.businessObject) {
            const loopCharacteristics = bpmnElement.businessObject.loopCharacteristics
            // 更新会签开关状态
            setIsMultiInstance(!!loopCharacteristics)

            if (loopCharacteristics) {
                setMultiInstanceConfig((prevState) => ({
                    ...prevState,
                    isSequential: loopCharacteristics.isSequential || false,
                    loopCardinality: loopCharacteristics.loopCardinality?.body || '',
                    collection: loopCharacteristics.collection || '',
                    elementVariable: loopCharacteristics.elementVariable || '',
                    completionCondition: loopCharacteristics.completionCondition?.body || '',
                }))
            } else {
                // 重置配置
                setMultiInstanceConfig((prevState) => ({
                    ...prevState,
                    isSequential: false,
                    loopCardinality: '',
                    collection: '',
                    elementVariable: '',
                    completionCondition: '',
                }))
            }
        }
        setBaseInfo({
            ...bpmnElement.businessObject,
        })

    }, [bpmnElement.businessObject]);
    useEffect(() => {
        if (isMultiInstance) {
            updateMultiInstance(multiInstanceConfig)
        } else {
            removeMultiInstance()
        }

    }, [multiInstanceConfig, isMultiInstance]);
    // 更新会签配置
    const updateMultiInstance = (config: Partial<MultiInstanceConfig>) => {
        if (!modeler || !bpmnElement) return
        // 创建或更新多实例特性
        const loopCharacteristics = moddle.create('bpmn:MultiInstanceLoopCharacteristics', {
            isSequential: config.isSequential,
            collection: config.collection,
            elementVariable: config.elementVariable,
        })

        if (config.loopCardinality) {
            const loopCardinality = moddle.create('bpmn:FormalExpression', {
                body: config.loopCardinality,
            })
            loopCharacteristics.loopCardinality = loopCardinality
        }

        if (config.completionCondition) {
            const completionCondition = moddle.create('bpmn:FormalExpression', {
                body: config.completionCondition,
            })
            loopCharacteristics.completionCondition = completionCondition
        }

        // 更新元素
        modeling.updateProperties(bpmnElement, {
            loopCharacteristics: loopCharacteristics,
        })
    }

    // 移除会签配置
    const removeMultiInstance = () => {
        if (!modeler || !bpmnElement) return

        modeling.updateProperties(bpmnElement, {
            loopCharacteristics: null,
        })
    }

    // 处理会签配置变更
    const handleMultiInstanceChange = (value: boolean) => {
        setIsMultiInstance(value)// 先更新状态
        // if (value) {
        //     // 开启会签
        //     updateMultiInstance({
        //         isSequential: false,
        //         loopCardinality: '',
        //         collection: '',
        //         elementVariable: '',
        //         completionCondition: '',
        //     })
        // } else {
        //     // 关闭会签
        //     removeMultiInstance()
        // }
    }

    // 处理会签配置更新
    const handleMultiInstanceUpdate = (key: string, value: any) => {
        setMultiInstanceConfig((prevState) => ({
            ...prevState,
            [key]: value,
        }))
    }


    const EventTypeList: DefaultOptionType[] = [
        {
            value: "message",
            label: '消息事件',
        }, {
            value: "signal",
            label: '信号事件',
        }, {
            value: "timer",
            label: '定时事件',
        },
    ]
    const timerDefinitionTypeList: DefaultOptionType[] = [
        {
            value: "timeDate",
            label: '日期',
        }, {
            value: "timeDuration",
            label: '持续时间',
        }, {
            value: "timeCycle",
            label: '循环',
        },
    ]
    const assigneeTypeMap = EventTypeList.reduce((acc, item) => {
        acc[item.value] = item.label;
        return acc;
    }, {} as Record<string, string>);
    return (
        <div className={baseInformationClass.listenerContainer}>
            <Card
                className={baseInformationClass.CardClass}
                title={`表单配置`}
                extra={null}>
                <Form>
                    <Form.Item
                        label="开启会签"
                        labelCol={{span: 6}}
                        wrapperCol={{span: 18}}>
                        <Switch value={isMultiInstance} checkedChildren="开启" unCheckedChildren="关闭" defaultChecked
                                onChange={handleMultiInstanceChange}/>
                    </Form.Item>
                    {isMultiInstance && (<>
                        <Form.Item
                            label="会签类型"
                            labelCol={{span: 6}}
                            wrapperCol={{span: 18}}>
                            <Radio.Group onChange={(e) => handleMultiInstanceUpdate("isSequential", e.target.value)}
                                         value={multiInstanceConfig.isSequential}>
                                <Radio value={false}>并行</Radio>
                                <Radio value={true}>串行</Radio>
                            </Radio.Group>
                        </Form.Item>
                        <Form.Item
                            label="循环次数"
                            labelCol={{span: 6}}
                            wrapperCol={{span: 18}}>
                            <Input
                                placeholder={"表达式，如：${nrOfInstances}"}
                                value={multiInstanceConfig.loopCardinality}
                                onChange={(e) => handleMultiInstanceUpdate("loopCardinality", e.target.value)}
                                suffix={
                                    <Tooltip title="支持表达式，如：${nrOfInstances}表示实例数量">
                                        <InfoCircleOutlined style={{color: 'rgba(0,0,0,.45)'}}/>
                                    </Tooltip>
                                }
                            />
                        </Form.Item>
                        <Form.Item
                            label="集合表达式"
                            labelCol={{span: 6}}
                            wrapperCol={{span: 18}}>
                            <Input
                                placeholder={"如：${assigneeList}"}
                                value={multiInstanceConfig.collection}
                                onChange={(e) => handleMultiInstanceUpdate("collection", e.target.value)}
                                suffix={
                                    <Tooltip title="支持表达式，如：${assigneeList}表示审批人列表">
                                        <InfoCircleOutlined style={{color: 'rgba(0,0,0,.45)'}}/>
                                    </Tooltip>
                                }
                            />
                        </Form.Item>
                        <Form.Item
                            label="元素变量"
                            labelCol={{span: 6}}
                            wrapperCol={{span: 18}}>
                            <Input
                                placeholder={"如：assignee"}
                                value={multiInstanceConfig.elementVariable}
                                onChange={(e) => handleMultiInstanceUpdate("elementVariable", e.target.value)}
                                suffix={
                                    <Tooltip title="集合中的每个元素在执行时的变量名">
                                        <InfoCircleOutlined style={{color: 'rgba(0,0,0,.45)'}}/>
                                    </Tooltip>
                                }
                            />
                        </Form.Item>
                        <Form.Item
                            label="完成条件"
                            labelCol={{span: 6}}
                            wrapperCol={{span: 18}}
                            tooltip={"支持表达式：${nrOfCompletedInstances}已完成数，${nrOfInstances}总实例数"}>
                            <Input.TextArea
                                placeholder={"请输入完成条件表达式，如：${nrOfCompletedInstances/nrOfInstances >= 0.6}"}
                                value={multiInstanceConfig.completionCondition}
                                onChange={(e) => handleMultiInstanceUpdate("completionCondition", e.target.value)}
                            />
                        </Form.Item>
                    </>)}
                </Form>
            </Card>

        </div>
    );
};

export default MultiInstanceConfigurationView;
